package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private static final String KEY_PREFIX= "user:verify:phone";

    @Override
    public Boolean isExits(String data, Integer type) {
    if (type !=1 && type !=2){
        //参数有误
        throw new LyException(400,"数据类型错误");
    }
        //select count(*)from tb_user where username = #{data}
        Integer count = query()
                .eq(type==1,"username", data)
                .eq(type==2,"phone", data)
                .count();
        //判断是否存在
        return count==1;
    }

    @Override
    public void sendVerifyCode(String phone) {
        //校验手机号格式
        if (!RegexUtils.isPhone(phone)){
            //手机号格式错误
            throw new LyException(400,"手机号格式错误");
        }
        //生成验证码
        String code = RandomStringUtils.randomNumeric(6);
        //调用amqpt发送短信
        Map<String ,String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,msg);
        //验证码存入redis
        redisTemplate.opsForValue().set(KEY_PREFIX +phone ,code, 5, TimeUnit.MINUTES);
    }

    @Override
    @Transactional
    public void register(User user, String code) {
        //校验用户验证码
        //取出redis验证码
        String cashCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        //比较
        if (!StringUtils.equals(cashCode,code)){
            throw new LyException(400,"验证码错误!");
        }
        //对密码加密,MD5 SHA
        //写入数据库
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //写入redis
        save(user);
    }

    @Override
    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        //先根据用户查询
        User user = query().eq("username", username).one();
        //判断结果
        if (user == null){
            //用户名错误
            throw new LyException(400,"用户名或密码错误！");
        }
        //校验密码
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        if (!matches){
            throw new LyException(400,"用户名或密码错误");
        }
        return new UserDTO(user);
    }
}